package com.ben.notebook.controller;

import com.ben.notebook.domain.Note;
import com.ben.notebook.domain.NoteCommands;
import com.ben.notebook.infrastructure.util.JsonResult;
import com.ben.notebook.infrastructure.util.JsonUtil;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import java.io.IOException;

/**
 * cqrs命令与查询职责分离
 * 命令都是实体的方法，每个方法都有一定的业务含义，
 * 查询则是直接来自mybatis，只是单纯获取数据
 * 此聚合根和相关数据的更新，若有其他领域数据需联动更新也放在同一个方法中，
 * 可使用发布-订阅模式实现多领域一致更新
 */
@RestController
@RequestMapping("note")
public class NoteCommandApi {

    private final NoteCommands commands;

    public NoteCommandApi(NoteCommands commands){
        this.commands = commands;
    }

    @PostMapping("/create")
    public JsonResult createNewNote(@RequestBody String noteJson) throws IOException {
        Note note = JsonUtil.jsonStr2Obj(noteJson, Note.class);
        int successNum = commands.create(note);
        //发布创建成功消息，进行其他操作如增加积分
        return JsonResult.ok(successNum);
    }

    @PostMapping("/modify")
    public JsonResult modifyNote(@RequestBody String noteJson) throws IOException {
        Note note = JsonUtil.jsonStr2Obj(noteJson, Note.class);
        return JsonResult.ok(commands.update(note));
    }

    @PostMapping("/delete")
    public JsonResult deleteNote(@RequestBody String noteJson) throws IOException {
        Note note = JsonUtil.jsonStr2Obj(noteJson, Note.class);
        int deleteNum = commands.delete(note);
        return JsonResult.ok(deleteNum);
    }

}
